package com.chapter.sample.jvm.gc;

import java.lang.ref.SoftReference;

/**
 * 软引用测试：内存不足即回收
 * -Xms10m  -Xmx10m -XX:+PrintGCDetails
 */
public class SoftReferenceTest {
    public static class User {
        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int id;
        public String name;

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //创建对象，建立软引用
        //SoftReference<User> userSoftReference = new SoftReference<>(new User(1,"sunwukong"));
        //上面的一行代码,等价于如下三行代码
        User user = new User(1, "sunwukong");
        SoftReference<User> softReference = new SoftReference<>(user);
        user = null;//取消强引用

        //从软引用中重写获取强引用对象
        System.out.println(softReference.get());

        System.gc();
        System.out.println("After GC：");

        //垃圾回收之后，获得软引用中的对象
        //由于堆空间内存足够，所以不会回收软引用的可达对象
        System.out.println(softReference.get());

        try {
            //让系统认为内存资源紧张，不够
            byte[] b = new byte[1024 * 7168 - 500 * 1024];


        }catch (Throwable throwable){
            throwable.printStackTrace();
        }finally {
            //再次从软引用中获取数据
            System.out.println(softReference.get());//在OOM之前,垃圾回收器会回收软引用的可达对象
        }

    }
}
